package com.tianma315.admin.material.controller;


import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import com.tianma315.admin.common.base.BaseController;
import com.tianma315.admin.common.utils.ResponseUtil;
import com.tianma315.admin.common.utils.Result;
import com.tianma315.admin.material.VO.PurchaseFileVO;
import com.tianma315.admin.material.VO.PurchaseVO;
import com.tianma315.admin.oss.service.FileService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tianma315.admin.material.domain.PurchaseDO;
import com.tianma315.admin.material.service.PurchaseService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * <pre>
 * 原材料进库表
 * </pre>
 * <small> 2019-05-25 15:23:18 | Aron</small>
 */
@Controller
@RequestMapping("/material/purchase")
public class PurchaseController extends BaseController{
	@Autowired
	private PurchaseService purchaseService;

	@Autowired
	private FileService sysFileService;
	
	@GetMapping()
	@RequiresPermissions("material:purchase:purchase")
	String Purchase(){
	    return "material/purchase/purchase";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("material:purchase:purchase")
	public Result<Page<PurchaseVO>> list(Integer pageNumber, Integer pageSize, String searchName){
        Page<PurchaseVO> page = purchaseService.getPurchaseVOPage(pageNumber,pageSize,searchName);
        return Result.ok(page);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("material:purchase:add")
	String add(){
	    return "material/purchase/add";
	}

	@GetMapping("/edit/{purchaseId}")
	@RequiresPermissions("material:purchase:edit")
	String edit(@PathVariable("purchaseId") Integer purchaseId,Model model){
		PurchaseDO purchase = purchaseService.selectById(purchaseId);
		model.addAttribute("purchase", purchase);
	    return "material/purchase/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("material:purchase:add")
	public Result<String> save(PurchaseDO purchase){
		//MultipartFile imageFile = fileVO.getFile();
//		try {
//
//			String url = "";
//			if (!imageFile.isEmpty()){
//				url = sysFileService.upload(imageFile.getBytes(),imageFile.getOriginalFilename());
//			}
			//PurchaseDO purchase = new PurchaseDO();
			//BeanUtils.copyProperties(fileVO,purchase);
//			purchase.setReportImg(url);
			purchase.setCreateBy(getUserId());
			purchase.setCreateDate(Calendar.getInstance().getTime());
			if(purchaseService.addPurchase(purchase)){
			    return Result.ok();
		    }

//		} catch (IOException e) {
//			e.printStackTrace();
//			return  Result.build(205,"文件上传失败");
//		}
		return Result.fail();
	}

	/**
	 * 跳转到多图片添加界面
	 * @param purchaseId
	 * @param model
	 * @return
	 */
	@GetMapping("/to_addReportImg/{purchaseId}")
	String toAddReportImg(@PathVariable("purchaseId")Integer purchaseId,Model model){
		model.addAttribute("id",purchaseId);
		return "material/purchase/uploadview";
	}

	/**
	 * 根据purchaseId 将图片地址更新到report_img字段中去
	 * @param request
	 * @param purchaseDO
	 * @return
	 */
	@PostMapping("/addReportImg/{purchaseId}")
	@ResponseBody
	Result addReportImg(HttpServletRequest request,PurchaseDO purchaseDO){
		purchaseService.insertImg(request,purchaseDO);
		return Result.ok();
	}

	/**
	 * 跳转到多图片修改界面
	 * @param purchaseId
	 * @param model
	 * @return
	 */
	@GetMapping("/to_updateReportImg/{purchaseId}")
	String toUpdateReportImg(@PathVariable("purchaseId")Integer purchaseId,Model model){
		PurchaseDO purchaseDO = purchaseService.selectById(purchaseId);
		String[] reportImg = purchaseDO.getReportImg().split(",");
		List<String> reportImgs  = new ArrayList<>(Arrays.asList(reportImg));
		model.addAttribute("reportImgs",reportImgs);
		model.addAttribute("purchaseId",purchaseId);
		return "material/purchase/updateimg";
	}

	/**
	 * 删除已有图片
	 * @param stat 根据编号（1,2,3）
	 * @param purchaseId 根据id
	 * @return
	 */
	@GetMapping("/deleteImg/{stat}/{purchaseId}")
	@ResponseBody
	Result deleteImg(@PathVariable("stat")Integer stat,@PathVariable("purchaseId")Integer purchaseId){
		PurchaseDO purchaseDO = purchaseService.selectById(purchaseId);
		//将字符串转换数组
		String[] reportImg = purchaseDO.getReportImg().split(",");
		//使用工具类ArrayUtils根据下标删除改图片地址
		reportImg = (String[]) ArrayUtils.remove(reportImg, stat-1);

		purchaseDO = new PurchaseDO();
		purchaseDO.setPurchaseId(purchaseId);

		//将返回的图片数组用逗号分隔转为字符串存入数据库中
		if (reportImg.length>0){
			String img="";
			for (int i = 0; i <reportImg.length ; i++) {
				img += reportImg[i]+",";
			}
			purchaseDO.setReportImg(img.substring(0,img.length()-1));
		}else{
			purchaseDO.setReportImg(null);
		}
		if (purchaseService.updatePurById(purchaseDO)){
			return Result.ok();
		}
		return Result.fail();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("material:purchase:edit")
	public Result<String>  update(PurchaseFileVO fileVO){
		MultipartFile imageFile = fileVO.getFile();
		String url = "";
//		try {
//			if (!imageFile.isEmpty()){
//				url = sysFileService.upload(imageFile.getBytes(),imageFile.getOriginalFilename());
//			}
			PurchaseDO purchase = new PurchaseDO();
			BeanUtils.copyProperties(fileVO,purchase);
//			purchase.setReportImg(url);
			purchase.setCreateBy(getUserId());
			purchase.setCreateDate(Calendar.getInstance().getTime());
			if(purchaseService.updateById(purchase)){
				return Result.ok();
			}

//		} catch (IOException e) {
//			e.printStackTrace();
//			return  Result.build(205,"文件上传失败");
//		}
		return Result.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("material:purchase:remove")
	public Result<String>  remove( Integer purchaseId){
		if(purchaseService.deletePurchase(purchaseId)){
            return Result.ok();
		}
		return Result.fail();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("material:purchase:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Integer[] purchaseIds){
		for (int i = 0; i < purchaseIds.length; i++) {
			purchaseService.deletePurchase(purchaseIds[i]);
		}
		return Result.ok();
	}

	/**
	 * 删除
	 */
	@GetMapping( "/getPurchaseList")
	@ResponseBody
	public Result<List<PurchaseDO>>  getPurchaseList(){
		Wrapper<PurchaseDO> wrapper = new EntityWrapper<>();
		wrapper.eq("state",0);
		List<PurchaseDO> purchaseDOList = purchaseService.selectList(wrapper);
		return Result.ok(purchaseDOList);
	}

	/**
	 * 导出模板
	 */
	@GetMapping( "/exportPurchase")
	public void exportPurchase(HttpServletResponse response){
		String fileName = "原材料导入模板.xls";
		try {
			response = ResponseUtil.getResponse(response,fileName);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		HSSFWorkbook wb =purchaseService.exportPurchase();
		try(OutputStream os = response.getOutputStream()) {
			wb.write(os);
			os.flush();
			os.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 进入导入excel
	 */
	@GetMapping( "/purchaseImport")
	public String purchaseImport(MultipartFile file){
		return "material/purchase/purchaseImport";
	}

	/**
	 * 导入excel
	 */
	@ResponseBody
	@PostMapping( "/importPurchase")
	public Result importPurchase(MultipartFile file){
		if (!file.isEmpty()){
			purchaseService.importPurchase(file,getUserId());
		}
		return Result.ok();
	}
	
}
